package com.shouer.doc.ui.ordermanager.presenter;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.R;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.ThreadPoolUtil;
import com.shouer.doc.event.CloseOrdEvent;
import com.shouer.doc.event.OrderUnReadCountEvent;
import com.shouer.doc.event.QueryUnReadCountEvent;
import com.shouer.doc.event.RollBackOrdEvent;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.healthreportedit.HealthReportEditActivity;
import com.shouer.doc.ui.neworder.model.HealthRecord;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;
import com.shouer.doc.ui.neworder.response.ReceiveOrderResponse;
import com.shouer.doc.ui.ordermanager.response.QueryFinisedOrderResponse;
import com.shouer.doc.ui.ordermanager.response.QueryOrderInOrderResponse;
import com.shouer.doc.ui.ordermanager.view.IOrderManagerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by ZXL on 2016/11/29.
 */

public class OrderManagerPresenterCompl implements IOrderManagerPresenter {

    private IOrderManagerView mOrderManagerView;
    private int currentPageNo1 = 1;//进行中订单查询分页数
    private int currentPageNo2 = 1;//已完成订单查询分页数
    private int maxPageNo = 10;
    private int pageNum = 20;
    private int pageNum2 = 50;

    private boolean isRefreshing1 = false;
    private boolean isLoadingMore1 = false;
    private boolean isRefreshing2 = false;
    private boolean isLoadingMore2 = false;

    public OrderManagerPresenterCompl(IOrderManagerView mOrderManagerView) {
        this.mOrderManagerView = mOrderManagerView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mOrderManagerView = null;
    }

    @Override
    public void queryOrderInOrder(int pageNo, int pageNum) {

        Log.d(OrderManagerPresenterCompl.class.getSimpleName(), "queryOrderInOrder");

        Map<String, String> param = new HashMap<>();
        param.put("pageNo", String.valueOf(pageNo));
        param.put("pageNum", String.valueOf(pageNum));
        param.put("docId", mOrderManagerView.getUser().getUserId());
        param.put("orderState", String.valueOf(ShouerConst.ORDER_STATE_DIAGNOSING));

        if (pageNo == 1) {
            isRefreshing1 = true;
        } else {
            isLoadingMore1 = true;
        }

        final GsonRequest<QueryOrderInOrderResponse> request = new GsonRequest("queryOrder", QueryOrderInOrderResponse.class, new Response.Listener<QueryOrderInOrderResponse>() {
            @Override
            public void onResponse(QueryOrderInOrderResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isRefreshing1 = false;
                isLoadingMore1 = false;
                mOrderManagerView.loadOrdInOrdFailed();
            }
        });

        RequestUtil.sendRequest(mOrderManagerView.getContext(), param, request);

    }

    @Override
    public void queryFinishedInOrder(int pageNo, int pageNum) {

        Map<String, String> param = new HashMap<>();
        param.put("pageNo", String.valueOf(pageNo));
        param.put("pageNum", String.valueOf(pageNum));
        param.put("docId", mOrderManagerView.getUser().getUserId());
        param.put("orderState", String.valueOf(ShouerConst.ORDER_STATE_CLOSED + "," + ShouerConst.ORDER_STATE_COMPLETED) + "," + String.valueOf(ShouerConst.ORDER_STATE_EVALUATED));

        if (pageNo == 1) {
            isRefreshing2 = true;
        } else {
            isLoadingMore2 = true;
        }

        final GsonRequest<QueryFinisedOrderResponse> request = new GsonRequest("queryOrder", QueryFinisedOrderResponse.class, new Response.Listener<QueryFinisedOrderResponse>() {
            @Override
            public void onResponse(QueryFinisedOrderResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isRefreshing2 = false;
                isLoadingMore2 = false;
                mOrderManagerView.loadFinishedOrderFailed();
            }
        });

        RequestUtil.sendRequest(mOrderManagerView.getContext(), param, request);

    }

    @Override
    public boolean refreshOrderInOrder() {
        if (isRefreshing1 || isLoadingMore1 || !mOrderManagerView.getApp().isUserLogin()) {
            return false;
        }
        queryOrderInOrder(1, pageNum2);
        return true;
    }

    @Override
    public boolean loadMoreOrderInOrder() {
        if (isRefreshing1 || isLoadingMore1 || (currentPageNo1 + 1) > maxPageNo || !mOrderManagerView.getApp().isUserLogin()) {
            return false;
        }
        queryOrderInOrder(currentPageNo1 + 1, pageNum2);
        return true;
    }

    @Override
    public boolean refreshFinishedOrder() {
        if (isRefreshing2 || isLoadingMore2 || !mOrderManagerView.getApp().isUserLogin()) {
            return false;
        }
        queryFinishedInOrder(1, pageNum);
        return true;
    }

    @Override
    public boolean loadMoreFinishedOrder() {
        if (isRefreshing2 || isLoadingMore2 || (currentPageNo2 + 1) > maxPageNo || !mOrderManagerView.getApp().isUserLogin()) {
            return false;
        }
        queryFinishedInOrder(currentPageNo2 + 1, pageNum);
        return true;
    }

    @Override
    public void onOrderInOrderItemClick(SimpleOrderModel orderModel) {

        if (mOrderManagerView.getApp().isUserLogin()) {
            if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_TUWEN || orderModel.getOrderType() == ShouerConst.ORDER_TYPE_YAO || orderModel.getOrderType() == ShouerConst.ORDER_TYPE_SHIPING) {
                if (orderModel.getOrderState() == ShouerConst.ORDER_STATE_DIAGNOSING ||
                            orderModel.getOrderState() == ShouerConst.ORDER_STATE_EVALUATED ||
                            orderModel.getOrderState() == ShouerConst.ORDER_STATE_CLOSED) {

                    String title = null;
                    if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_YAO) {
                        title = mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_YAO);//挂号送药
                    } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_SHIPING) {
                        title =  mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_SHIPING);//视频咨询
                    } else if (orderModel.getOrderType() == ShouerConst.ORDER_TYPE_DIANHUA) {
                        title =  mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_DIANHUA);//电话咨询
                    } else {
                        if (orderModel.getChannel()==9)
                        {
                            title =  mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_HEALTHRECORD);//健康报告咨询
                        }else {
                            if ("0".equals(orderModel.getFreeType())) {
                                title =  mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_TUWEN_FREE);//免费导诊
                            } else {
                                title =  mOrderManagerView.getContext().getResources().getString(R.string.ORDER_NAME_TUWEN);//图文咨询
                            }
                        }

                    }

                    Uri uri = Uri.parse("rong://" + mOrderManagerView.getContext().getApplicationInfo().packageName).buildUpon().appendPath("conversation").appendPath(Conversation.ConversationType.GROUP.getName().toLowerCase()).
                                appendQueryParameter("targetId", orderModel.getOrderId()).appendQueryParameter("title", title).build();
                    Intent intent = new Intent("android.intent.action.VIEW", uri);
                    intent.putExtra("order_info", orderModel);
                    mOrderManagerView.getContext().startActivity(intent);
                    orderModel.setUnReadCount(0);
                    EventBus.getDefault().post(orderModel);
                }
            }
        }
    }

    @Override
    public void onHealthRecordItemClick(HealthRecord healthRecord) {

        Intent intent=new Intent(mOrderManagerView.getContext(), HealthReportEditActivity.class);
        intent.putExtra("recId",healthRecord.getRecid());
        mOrderManagerView.getContext().startActivity(intent);
    }

    @Override
    public void refreshUnReadCount(final SimpleOrderModel orderModel) {
        ThreadPoolUtil.getInstance().getCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                RongIM.getInstance().getUnreadCount(Conversation.ConversationType.GROUP, orderModel.getOrderId(), new RongIMClient.ResultCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        if (integer > 0) {
                            orderModel.setUnReadCount(integer);
                            EventBus.getDefault().post(orderModel);
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                    }
                });
            }
        });


    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBackgroundThread(final QueryUnReadCountEvent event)
    {
        ThreadPoolUtil.getInstance().getCachedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                RongIM.getInstance().getUnreadCount(Conversation.ConversationType.GROUP, event.getOrderId(), new RongIMClient.ResultCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer integer) {
                        if (integer > 0) {
                            EventBus.getDefault().post(new OrderUnReadCountEvent(event.getOrderId(),integer));
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                    }
                });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryOrderInOrderResponse response) {
        isRefreshing1 = false;
        isLoadingMore1 = false;
        if (response.getErrorCode() >= 0) {
            if (response.getPageNo() == 1) {
                currentPageNo1 = 1;
                mOrderManagerView.refreshOrdInOrdList(response.getOrderInfoList());
            } else {
                if (null != response.getOrderInfoList() && response.getOrderInfoList().size() > 0) {
                    currentPageNo1++;
                }
                mOrderManagerView.attachOrdIOrdList(response.getOrderInfoList());
            }
        } else {
            mOrderManagerView.loadOrdInOrdFailed();
            Toast.makeText(mOrderManagerView.getContext(), response.getErrorMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryFinisedOrderResponse response) {
        isRefreshing2 = false;
        isLoadingMore2 = false;
        if (response.getErrorCode() >= 0) {
            if (response.getPageNo() == 1) {
                currentPageNo2 = 1;
                mOrderManagerView.refreshFinishedOrdList(response.getOrderInfoList());
            } else {
                if (null != response.getOrderInfoList() && response.getOrderInfoList().size() > 0) {
                    currentPageNo2++;
                }
                mOrderManagerView.attachFinishedOrdList(response.getOrderInfoList());
            }
        } else {
            mOrderManagerView.loadFinishedOrderFailed();
            Toast.makeText(mOrderManagerView.getContext(), response.getErrorMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 在新订单页面接单成功的话则刷新进行中订单列表页
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ReceiveOrderResponse response) {
        if (response.getErrorCode() >= 0) {
            refreshOrderInOrder();
        }
    }

    /**
     * 关闭订单消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CloseOrdEvent event) {
        refreshFinishedOrder();
        mOrderManagerView.getOrdInOrderAdapter().removeOrderById(event.getOrderId());
    }

    /**
     * 订单回退
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RollBackOrdEvent event) {
        refreshFinishedOrder();
        mOrderManagerView.getOrdInOrderAdapter().removeOrderById(event.getOrderId());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SimpleOrderModel orderModel) {
        mOrderManagerView.refreshOrdItem(orderModel);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(OrderUnReadCountEvent event) {
        mOrderManagerView.refreshUnReadCount(event.getOrderId(),event.getCount());
    }
}
